#ifndef _WUXI_AGET_INIT_H_
#define _WUXI_AGET_INIT_H_

#include "http.h"

/**
 * protocols:
 */
#define AGET_HTTP  1
#define AGET_HTTPS 2
#define AGET_FTP   3

extern int AGET_DEBUG;


/**
 * debug output if global variable AGET_DEBUG is not 0.
 */
void dprintf(char* fmt, ...);

/**
 * program basic options:
 */
struct agetopt_t {
    int          sck;      /**< socket */
    int          prot;     /**< protocal */
    char*        uri;      /**< URI */
    char*        host;     /**< host */
    char*        path;     /**< path */
    unsigned int port;     /**< connect port */
    int          retry;    /**< retry times */
    int          timeout;  /**< timeout second */
    int          offset;   /**< continue offset */
    FILE*        fp;       /**< output file */
    FILE*        fh;       /**< header output file */
    FILE*        savecookie; /**< set-cookie output file */
} agetopt;


/**
 * initialize, sets default values to settings. and returns a opened socket.
 */
int init(void);

/**
 * cleanup
 */
void cleanup(void);


/**
 * interpret val as int and set to a.
 */
void intopt(int* a, const char* val);

/**
 * copy val to a;
 */
void stringopt(char** a, const char* val);

/**
 * set bool option a.
 */
void boolopt(int* a);

/**
 * open a file. first try to open it as r+ and the set the writing pointer
 * to the end of the file, if it failed, then try to open it as w, if it
 * still failed, returns NULL. If filename=="-" it opens stdout, or if
 * filename=="*" it sets to agetopt.fp.
 */
FILE* openfile(const char* filename);

/**
 * parse url to get protocol, host name, port and path
 *
 * @return int, value indicate the protocol.
 * @retval -1 unknown protocol.
 * @retval 0 no protocol specified.
 * @retval 1 http
 * @retval 2 https
 * @retval 3 ftp
 */
int parse_uri(char* uri, char** host, unsigned int* port, char** path);

/**
 * retrieve data.
 *
 * @return int. result.
 * @retval 0 if succeed, otherwise returns a negative number indicates error.
 * @retval -1 if failed on gethostbyname.
 * @retval -2 if unknown address type.
 *
 * @note When it returns a negative number other than -1, the errno will be set.
 *       Returning -1 indicates error occurs on invoking 'gethostbyname'.
 */
int aget(HTTP* http, httpopt_t* hopt);


#endif
